ZendFramewok2 – 微维WeiVa http://www.weiva.com Micro Thinking Tue, 25 Feb 2020 06:12:45 +0000 zh-CN hourly 1 https://wordpress.org/?v=4.8.25 http://www.weiva.com/wp-content/uploads/2017/04/cropped-logo640-32x32.png ZendFramewok2 – 微维WeiVa http://www.weiva.com 32 32 ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/227 http://www.weiva.com/archives/227#respond Sun, 27 Sep 2015 08:52:17 +0000 http://www.weiva.com/?p=227 继续阅读“Zend Framework2 中的Repository仓库模式及分页应用”

]]>
Zend Framework2 中的Repository仓库模式

Repository仓库模式是提供将多个、一批资源雷竞技苹果下载地址作为集合使用的一种雷竞技苹果下载地址使用模式,在对资源进行浏览、查询、搜索以及输出到页面时非常有用,符合人们的正常思维逻辑。

使用Repository模式对Entity管理的步骤:

1、仓库类的目录
在ZendFramework2中,Doctrine2的Repository类存放在模块的src/Entity/Repository目录下。

2、使用仓库进行分页
配置路由
在路由中添加路由参数page

在实体中指定仓库

/** @ORMEntity(repositoryClass="YourModuleEntityRepositoryYourRepository")
*/
class YourEntity {
}

在项目模块的src模块名 下创建目录 Paginator,添加Doctrine2分页适配器 Adapter.php,其内容如下:

<?php
namespace YouModulePaginator;

use DoctrineORMEntityRepository;
use ZendPaginatorAdapterAdapterInterface;
class Adapter implements AdapterInterface{
    protected  $repository;

    /**
     * @param EntityRepository $repository
     */
    function __construct($repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param int $offset               Page offset
     * @param int $itemCountPerPage     Number of items per page
     * @return array
     */
    public function getItems($offset,$itemCountPerPage){
        return $this->repository->getItems($offset,$itemCountPerPage);
    }

    /**
     * @return int
     */
    public function count(){
        return $this->repository->count();
    }
}

在模块文件 module.php 中添加分页助手的工厂模式:

                    'YourModulePaginatorYouEntity'=>function($sm){
                        $enm = $sm->get('DoctrineORMEntityManager');
                        $YouEntityRepository = $enm->getRepository('YourModuleEntityYouEntity');
                        $adapter = new YourModulePaginatorAdapter($YourEntityRepository);
                        $page = $sm->get('application')
                            ->getMvcEvent()
                            ->getRouteMatch()
                            ->getParam('page');
                        $paginator = new Paginator($adapter);
                        $itemCountPerPage = 10;//每页项目数
                        $paginator->setCurrentPageNumber($page)
                            ->setItemCountPerPage($itemCountPerPage);
                        return $paginator;
                    }

添加分页翻页模板 viewmoduleNamepartialspaginator.phtml

修改控制器的action

]]>
http://www.weiva.com/archives/227/feed 0
ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/202 http://www.weiva.com/archives/202#respond Fri, 18 Sep 2015 17:17:36 +0000 http://www.weiva.com/?p=202 继续阅读“Doctrine 2 ORM 2 文档 5. Association Mapping 非专业局部翻译”

]]>
原文地址:http://docs.doctrine-project.org/en/latest/reference/association-mapping.html

注:本文只针对本人使用到的关系类型进行翻译,未使用到的以后有空再补上。

5. Association Mapping

This chapter explains mapping associations between objects.
这一章节介绍雷竞技苹果下载地址之间的关系映射。

Instead of working with foreign keys in your code, you will always work with references to objects instead and Doctrine will convert those references to foreign keys internally.
你将使用雷竞技苹果下载地址关联(references)和Doctrine替代你原来代码中数据库外键的工作。

  • A reference to a single object is represented by a foreign key.
    一个关联到单个雷竞技苹果下载地址对应一个数据库的外键。
  • A collection of objects is represented by many foreign keys pointing to the object holding the collection
    一个雷竞技苹果下载地址的集合代表许多外键指向这个雷竞技苹果下载地址所在的集合。
  • This chapter is split into three different sections.
    本章分为三个不同的部分:

  • A list of all the possible association mapping use-cases is given.
    所有可用的雷竞技苹果下载地址映射关系列表
  • Mapping Defaults are explained that simplify the use-case examples.
    默认映射介绍简单的使用实例。
  • Collections are introduced that contain entities in associations.
    集合介绍链接实体映射。
  • To gain a full understanding of associations you should also read about owning and inverse sides of associations
    如果需要完全了解雷竞技苹果下载地址映射,你可以阅读owning and inverse sides of associations

    目录
    5.1. Many-To-One, Unidirectional 多对一,单向(用户 对 地址)
    5.2. One-To-One, Unidirectional 一对一,单向()
    5.3. One-To-One, Bidirectional 一对一,双向(顾客 对 购物车)
    5.4. One-To-One, Self-referencing 一对一,自指向
    5.5. One-To-Many, Bidirectional 一对多,双向(产品 对 特点)
    5.6. One-To-Many, Unidirectional with Join Table 一对多,使用表的单向
    5.7. One-To-Many, Self-referencing 一对多,自指向(层级分类、文章栏目分类)
    5.8. Many-To-Many, Unidirectional 多对多,单向
    5.9. Many-To-Many, Bidirectional 多对多,双向
    5.9.1. Owning and Inverse Side on a ManyToMany association
    5.10. Many-To-Many, Self-referencing 多对多,自指向
    5.11. Mapping Defaults 默认映射
    5.12. Collections 集合
    5.13. Initializing Collections 初始化集合

    PS:
    一对多和多对一底层数据库结构完全一样,都是在[多]方创建外键;
    一对多只提供[一]方对[多]方的访问,[多]方没有[一]方的引用.如果有,就变成双向关联了;
    只需在[一]方配置,[多]方不需要;

    5.1. Many-To-One, Unidirectional
    5.1. 多对一,单向

    A many-to-one association is the most common association between objects.
    多对一映射是非常常见的雷竞技苹果下载地址关系。

    <?php
    /** @Entity **/
    class User
    {
        // ...
    
        /**
         * @ManyToOne(targetEntity="Address")
         * @JoinColumn(name="address_id", referencedColumnName="id")
         **/
        private $address;
    }
    
    /** @Entity **/
    class Address
    {
        // ...
    }
    

    The above @JoinColumn is optional as it would default to address_id and id anyways. You can omit it and let it use the defaults.
    上述代码中的 @JoinColumn 是设置默认映射使用User.address_id关联到Address.id,你可以删除它,以使用默认值。

    Generated MySQL Schema:
    生成的 MySQL 代码:

    CREATE TABLE User (
    id INT AUTO_INCREMENT NOT NULL,
    address_id INT DEFAULT NULL,
    PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    
    CREATE TABLE Address (
    id INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    
    ALTER TABLE User ADD FOREIGN KEY (address_id) REFERENCES Address(id);
    

    5.7. One-To-Many, Self-referencing
    5.7. 一对多,自指向

    You can also setup a one-to-many association that is self-referencing. In this example we setup a hierarchy of Category objects by creating a self referencing relationship. This effectively models a hierarchy of categories and from the database perspective is known as an adjacency list approach.
    你可以设置自指向的关系映射。在本例中,将创建一个使用自指向的层级的分类雷竞技苹果下载地址映射关系。可以在数据库的关系视图中看到他们的层级关系。
    PS:这个关系的典型应用应该是文章的栏目分类、用户角色等树状结构。

    &lt;?php
    /** @Entity **/
    class Category
    {
        // ...
        /**
         * @OneToMany(targetEntity="Category", mappedBy="parent")
         **/
        private $children;
    
        /**
         * @ManyToOne(targetEntity="Category", inversedBy="children")
         * @JoinColumn(name="parent_id", referencedColumnName="id")
         **/
        private $parent;
        // ...
    
        public function __construct() {
            $this-&gt;children = new DoctrineCommonCollectionsArrayCollection();
        }
    }
    

    Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.
    例子中的 @JoinColumn 可不写,默认值也是这样。

    Generated MySQL Schema:
    生成的 MySQL 代码:

    CREATE TABLE Category (
        id INT AUTO_INCREMENT NOT NULL,
        parent_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Category ADD FOREIGN KEY (parent_id) REFERENCES Category(id);
    
    ]]>
    http://www.weiva.com/archives/202/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/188 http://www.weiva.com/archives/188#respond Fri, 18 Sep 2015 04:20:51 +0000 http://www.weiva.com/?p=188 继续阅读“基于 ZendFramework2 框架搭建网站系统的步骤”

    ]]>
    ZendFramework2(ZF2) 是 php 东家 zend 公司的亲儿子框架,网上介绍也比较多,这里就不再重复了。国内使用比较少,确实比较庞大和臃肿,但是在辗转其他一些 php 开源框架后,还是决定使用ZF2。下面将现在我正在开发的项目流程做一个简要的记录:

    一、使用ZF2官方提供的 Skeleton Application 搭建基本网站结构

    这一步网上的教程比较多,官网也说得比较清楚,这里不再详述。安装完成后,你就拥有了一个基于ZF2框架的MVC系统。
    官网链接:Get the Skeleton Application

    二、安装和配置 Doctrine 2 

    这一步是让系统实现 ORM 的开发模式。

    三、安装zfc-user 、zfc-user-doctrine-orm、BjyAuthorize

    完成这一步以后,你得系统就拥有了基于 ORM 模式的用户-角色权限功能。

    其他参考:
    Dortrine 2 命令行常用命令说明
    ZfcUser配置文件不完全不专业翻译

    外站参考:
    ZendFramework2 官网    手册   API参考


    ZendFramework2 模块
     


    Doctrine2 官网
    Doctrine logo

    ]]>
    http://www.weiva.com/archives/188/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/177 http://www.weiva.com/archives/177#respond Thu, 17 Sep 2015 18:41:08 +0000 http://www.weiva.com/?p=177 ZfcUser 项目地址:https://github.com/ZF-Commons/ZfcUser

    <?php
    /**
     * ZfcUser Configuration
     *
     * If you have a ./config/autoload/ directory set up for your project, you can
     * drop this config file in it and change the values as you wish.
     */
    $settings = array(
        /**
         * ZendDbAdapterAdapter DI Alias
         *
         * Please specify the DI alias for the configured ZendDbAdapterAdapter
         * instance that ZfcUser should use.
         */
        //'zend_db_adapter' => 'ZendDbAdapterAdapter',
    
        /**
         * User Model Entity Class
         * 用户实体类
         *
         * Name of Entity class to use. Useful for using your own entity class
         * instead of the default one provided. Default is ZfcUserEntityUser.
         * The entity class should implement ZfcUserEntityUserInterface
         * 指定哪个类为用户实体类。可以使用你自己的类来替换系统提供的。默认是
         * ZfcUserEntityUser。这个类实现了 ZfcUserEntityUserInterface 接口。
         */
        //'user_entity_class' => 'ZfcUserEntityUser',
        //'user_entity_class' => 'IchcmsEntityUser',
    
        /**
         * Enable registration
         * 是否开启注册
         *
         * Allows users to register through the website.
         *
         * Accepted values: boolean true or false
         */
        //'enable_registration' => true,
    
        /**
         * Enable Username
         * 是否开启用户名(默认不开启)
         *
         * Enables username field on the registration form, and allows users to log
         * in using their username OR email address. Default is false.
         * 开启后用户名将出现在注册表单中,并且允许用户使用用户名或者邮箱进行登录。
         *
         * Accepted values: boolean true or false
         */
        //'enable_username' => false,
    
        /**
         * Authentication Adapters
         * 鉴权适配器
         *
         * Specify the adapters that will be used to try and authenticate the user
         * 指定用于鉴权的适配器
         *
         * Default value: array containing 'ZfcUserAuthenticationAdapterDb' with priority 100
         * Accepted values: array containing services that implement 'ZfcUserAuthenticationAdapterChainableAdapter'
         */
        'auth_adapters' => array( 100 => 'ZfcUserAuthenticationAdapterDb' ),
    
        /**
         * Enable Display Name
         * 是否开启昵称(默认关闭)
         *
         * Enables a display name field on the registration form, which is persisted
         * in the database. Default value is false.
         * 开启后,昵称表单将显示在注册表单,昵称将存储在数据库。
         * Accepted values: boolean true or false
         */
        //'enable_display_name' => true,
    
        /**
         * Modes for authentication identity match
         * 设置身份鉴权的id匹配模式
         *
         * Specify the allowable identity modes, in the order they should be
         * checked by the Authentication plugin.
         * 设置可以使用作为身份鉴权的id模式,将提供给鉴权适配器使用。
         * Default value: array containing 'email'
         * Accepted values: array containing one or more of: email, username
         * 值是一个数组,默认是 email,可以指定包括 email,username在内的一个或者多个选项
         */
        //'auth_identity_fields' => array( 'email' ),
    
        /**
         * Login form timeout
         * 设置登录超时
         *
         * Specify the timeout for the CSRF security field of the login form
         * in seconds. Default value is 300 seconds.
         *
         * Accepted values: positive int value
         */
        //'login_form_timeout' => 300,
    
        /**
         * Registration form timeout
         * 设置注册超时
         *
         * Specify the timeout for the CSRF security field of the registration form
         * in seconds. Default value is 300 seconds.
         *
         * Accepted values: positive int value
         */
        //'user_form_timeout' => 300,
    
        /**
         * Login After Registration
         * 设置注册成功后是否自动登录(默认是)
         *
         * Automatically logs the user in after they successfully register. Default
         * value is false.
         *
         * Accepted values: boolean true or false
         */
        //'login_after_registration' => true,
    
        /**
         * Registration Form Captcha
         * 是否使用验证码注册
         *
         * Determines if a captcha should be utilized on the user registration form.
         * Default value is false.
         * 指定是否显示一个验证码在用户注册表单,默认是否
         */
        //'use_registration_form_captcha' => false,
    
        /**
         * Form Captcha Options
         * 设置表单验证码
         *
         * Currently used for the registration form, but re-usable anywhere. Use
         * this to configure which ZendCaptcha adapter to use, and the options to
         * pass to it. The default uses the Figlet captcha.
         * 此设置作用在注册表单,但是也可以用在其他地方。这里设置将对 ZendCaptcha 模块起作用。
         * 注:默认提供的验证码并不是图片,而是非常囧的文字图验证码。
         *
         *
         */
        /*'form_captcha_options' => array(
            'class'   => 'figlet',
            'options' => array(
                'wordLen'    => 5,
                'expiration' => 300,
                'timeout'    => 300,
            ),
        ),*/
    
        /**
         * Use Redirect Parameter If Present
         * 设置是否重定向跳转
         *
         * Upon successful authentication, check for a 'redirect' POST or GET parameter
         * 如果登录成功,按照 POST 或者 GET 数据中是否存在 redirect 参数进行跳转。
         * 默认是是。
         *
         * Accepted values: boolean true or false
         */
        //'use_redirect_parameter_if_present' => true,
    
        /**
    	 * Sets the view template for the user login widget
         * 设置用户登录的视图模板
    	 *
    	 * Default value: 'zfc-user/user/login.phtml'
         * Accepted values: string path to a view script
    	 */
        //'user_login_widget_view_template' => 'zfc-user/user/login.phtml',
    
        /**
         * Login Redirect Route
         * 登录后的重定向路由
         *
         * Upon successful login the user will be redirected to the entered route
         *
         * Default value: 'zfcuser'
         * Accepted values: A valid route name within your application
         *
         */
        //'login_redirect_route' => 'zfcuser',
    
        /**
         * Logout Redirect Route
         * 注销后的重定向路由
         *
         * Upon logging out the user will be redirected to the entered route
         *
         * Default value: 'zfcuser/login'
         * Accepted values: A valid route name within your application
         */
        //'logout_redirect_route' => 'zfcuser/login',
    
        /**
         * Password Security
         * 密码安全
         *
         * DO NOT CHANGE THE PASSWORD HASH SETTINGS FROM THEIR DEFAULTS
         * Unless A) you have done sufficient research and fully understand exactly
         * what you are changing, AND B) you have a very specific reason to deviate
         * from the default settings and know what you're doing.
         *
         * The password hash settings may be changed at any time without
         * invalidating existing user accounts. Existing user passwords will be
         * re-hashed automatically on their next successful login.
         */
    
        /**
         * Password Cost
         *
         * The number represents the base-2 logarithm of the iteration count used for
         * hashing. Default is 14 (about 10 hashes per second on an i5).
         *
         * Accepted values: integer between 4 and 31
         */
        //'password_cost' => 14,
    
        /**
         * Enable user state usage
         * 是否使用用户状态功能(视乎默认未开启)
         *
         * Should user's state be used in the registration/login process?
         */
        //'enable_user_state' => true,
    
        /**
         * Default user state upon registration
         * 用户注册后的默认状态值(默认1),数据库对应 state 字段
         *
         * What state user should have upon registration?
         * Allowed value type: integer
         */
        //'default_user_state' => 1,
    
        /**
         * States which are allowing user to login
         * 哪一种状态值的用户允许登录(默认1)
         *
         * When user tries to login, is his/her state one of the following?
         * Include null if you want user's with no state to login as well.
         * Allowed value types: null and integer
         */
        //'allowed_login_states' => array( null, 1 ),
    
        /**
         * User table name
         * 用户数据表
         */
        //'table_name' => 'user',
    
        /**
         * End of ZfcUser configuration
         */
    );
    
    /**
     * You do not need to edit below this line
     */
    return array(
        'zfcuser' => $settings,
        'service_manager' => array(
            'aliases' => array(
                'zfcuser_zend_db_adapter' => (isset($settings['zend_db_adapter'])) ? $settings['zend_db_adapter']: 'ZendDbAdapterAdapter',
            ),
        ),
    );
    
    
    ]]>
    http://www.weiva.com/archives/177/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/172 http://www.weiva.com/archives/172#respond Thu, 17 Sep 2015 17:18:44 +0000 http://www.weiva.com/?p=172 继续阅读“ZendFramework 2 下安装zfc-user 、zfc-user-doctrine-orm、BjyAuthorize”

    ]]>
    简介:
    zfc是ZendFramework 2 标准模块外提供的公共库,即 Zend Framework Common,包含了一些常用的功能块,例如 user、rabc 等功能。
    zfc-user:zfc中的用户功能,提供了基于数据库的用户鉴权、用户登录、注销等基本的功能。
    zfc-user-doctrine-orm:为 zfc-user 提供 doctrine orm 模式的模块,能够使用户功能通过指定的用户实体(Entity)进行持久化存储。
    BjyAuthorize :为 zfc-user 提供基于角色-用户(Role-User)的用户、权限管理模块,支持指定  doctrine orm 的用户、角色实体(Entity)。开发者可以指定和扩展自己的 User 、Role 类。

    一、安装zfc-user-doctrine-orm 、bjy-authorize模块

    1、安装这两个模块前必须安装并配置好 Doctrine ORM,具体步骤参考:ZendFramework 2 下安装和配置 Doctrine 2 的步骤

    2、安装模块库

    zfc-user-doctrine-orm

    php composer.phar require zf-commons/zfc-user-doctrine-orm 

    bjy-authorize

    php composer.phar require bjyoungblood/bjy-authorize:1.4.* 

    (注:如果已经配置好全局使用composer,注意更改前段的命令)

    二、配置模块

    修改:config/application/application.config.php, 像下面这样:

    'modules' => array(
        'DoctrineModule',
        'DoctrineORMModule',
        'ZfcBase',
        'ZfcUser',
        'ZfcUserDoctrineORM',,
        'BjyAuthorize',
        'Application',
    ),
    

    三、配置数据库

    有两种方法,推荐第二种:

    第一种:在MySql中执行以下SQL:

    (原文件链接: ZfcUser SQL schema )

    SQL:

    CREATE TABLE `user`
    (
        `user_id`       INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `username`      VARCHAR(255) DEFAULT NULL UNIQUE,
        `email`         VARCHAR(255) DEFAULT NULL UNIQUE,
        `display_name`  VARCHAR(50) DEFAULT NULL,
        `password`      VARCHAR(128) NOT NULL,
        `state`         SMALLINT UNSIGNED
    ) ENGINE=InnoDB CHARSET="utf8";
    

    第二种:使用 doctrine-module 来配置:

    1、尝试输出 SQL

    vendor/bin/doctrine-module orm:schema-tool:update --dump-sql 

    如果是在win系统

    vendorbindoctrine-module.bat orm:schema-tool:update --dump-sql 

    提示:如果你希望使用不同的表结构或者用户实体,你可以在 zfcuser 的config 文件 中设置参数 enable_default_entities(后文会有提到) 。

    2、执行 ORM 数据库同步

    如果上一条命令能够正确的输出数据库SQL命令,那么久表示设置好了,执行下面的命令同步数据库:

    vendor/bin/doctrine-module orm:schema-tool:update --force 

    如果是在win系统

    vendorbindoctrine-module.bat orm:schema-tool:update --force 

    你现在可以使用路由 /user 路由来访问zfc-user模块了

    四、配置 BjyAuthorize
    1、复制 BjyAuthorize 模块目录 data 下的文件 User.php.dist, Role.php.dist 到你自己的模块的 Entity 目录下。并分别更名为 User.php, Role.php。
    修改文件 User.php、Role.php 的命名空间 namespace 你的模块名Entity
    修改 User.php 文件中的 Role 字段的注释 targetEntity=”你的模块名EntityRole”
    修改 Role.php 文件中的 parent字段的注释 targetEntity=”你的模块名EntityRole”,

    2、在你自己的模块配置文件添加以下配置:

     /* 部署 BjyAuthorize */
        'doctrine' => array(
            'driver' => array(
                // overriding zfc-user-doctrine-orm's config
                'zfcuser_entity' => array(
                    'class' => 'DoctrineORMMappingDriverAnnotationDriver',
                    'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity',
                    ),
                ),
    
                'orm_default' => array(
                    'drivers' => array(
                         __NAMESPACE__ . 'Entity' => 'zfcuser_entity'
                    ),
                ),
            ),
        ),
    
        'zfcuser' => array(
            // telling ZfcUser to use our own class
            'user_entity_class'       => __NAMESPACE__.'EntityUser',
            // telling ZfcUserDoctrineORM to skip the entities it defines
            'enable_default_entities' => false,
        ),
    
        'bjyauthorize' => array(
            // Using the authentication identity provider, which basically reads the roles from the auth service's identity
            'identity_provider' => 'BjyAuthorizeProviderIdentityAuthenticationIdentityProvider',
    
            'role_providers'        => array(
                // using an object repository (entity repository) to load all roles into our ACL
                'BjyAuthorizeProviderRoleObjectRepositoryProvider' => array(
                    'object_manager'    => 'doctrine.entitymanager.orm_default',
                    'role_entity_class' => __NAMESPACE__.'EntityRole',
                ),
            ),
        )
    

    3、同步数据库

    vendor/bin/doctrine-module orm:schema-tool:update --force 

    4、添加角色数据到数据库(根据需要修改)

    INSERT INTO `role`
        (`id`, `parent_id`, `roleId`)
    VALUES
        (1, NULL, 'guest'),
        (2, 1, 'user'),
        (3, 2, 'moderator'),
        (4, 3, 'administrator');
    

    五、使用路由 /user 访问网站
    注册和使用用户
    如果需要调整用户的角色,需要手工调整数据表 user_role_linker

    ]]>
    http://www.weiva.com/archives/172/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/163 http://www.weiva.com/archives/163#respond Thu, 17 Sep 2015 15:08:04 +0000 http://www.weiva.com/?p=163 继续阅读“ZendFramework 2 下安装和配置 Doctrine 2 的步骤”

    ]]>
    一、确保 composer 正常

    要确保 composer 能够正常的使用,如果因为GFW原因,可以尝试修改composer.json ,使用国内的镜像:

    
    "repositories": [
    {"type": "composer", "url": "http://packagist.phpcomposer.com"},
    {"packagist": false}
    
    

    二、添加模块依赖
    直接上 composer 代码,以下配置内容加上了 zend-developer-tools、zftool、bj-profiler的模块依赖,这些模块配置很简单,官网上面都有,照着做就可以了。如果不需要,可以删除。

    
    {
        "name": "Your project name",
        "description": "Your project description",
        "license": "BSD-3-Clause",
        "keywords": [
            ""
        ],
        "homepage": "Your project homepage",
        "require": {
            "php": ">=5.5",
            "zendframework/zendframework": "~2.5",
            "zendframework/zend-developer-tools": "dev-master",
            "zendframework/zftool": "dev-master",
            "bjyoungblood/bjy-profiler": "dev-master",
            "doctrine/doctrine-orm-module": "^0.9.1"
        },
        "repositories": [
            {"type": "composer", "url": "http://packagist.phpcomposer.com"},
            {"packagist": false}
        ]
    }
    
    

    三、修改 local.php 配置文件
    如果没有local.php,就创建一个

    
    $dbParams = array(
        'dbname' => 'dbname',
        'dbuser' => 'dbuser',
        'dbpass' => 'dbpass',
        'dbhost' => 'dbhost',
        'dbport' => 'dbport',
        // buffer_results - only for mysqli buffered queries, skip for others
        'options' => array(
            'buffer_results' => true
        )
    );
    
    return array(
        'dbParams'=>$dbParams,
        'doctrine' => array(
            'connection' => array(
                'orm_default' => array(
                    'driverClass' => 'DoctrineDBALDriverPDOMySqlDriver',
                    'params' => array(
                        'host' => $dbParams['dbhost'],
                        'port' => $dbParams['dbport'],
                        'user' => $dbParams['dbuser'],
                        'password' => $dbParams['dbpass'],
                        'dbname' => $dbParams['dbname'],
                        'charset' => 'UTF8'
                    )
                )
            )
        )
    );
    
    

    四、修改模块配置文件
    修改需要使用 Doctrine 的模块目录下的 config 子目录的配置文件 module.config.php,添加配置内容如下:

    return array(
        /** 其他配置内容 **/
        /**
            * 部署 Doctrine
        */
        'doctrine' => array(
    		'driver' => array(
    		  __NAMESPACE__ . '_driver' => array(
    			'class' => 'DoctrineORMMappingDriverAnnotationDriver',
    			'cache' => 'array',
    			'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity',  // Define path of entities
    			)
    		  ),
    		  'orm_default' => array(
    			'drivers' => array(
    			  __NAMESPACE__ . 'Entity' => __NAMESPACE__ . '_driver'  // Define namespace of entities
    			)
    		  )
    		)
    	)
    );
    

    上述配置指定了该模块的 雷竞技苹果下载地址 Entty 目录在模块目录下的 src/模块名称/Entity 目录下

    ]]>
    http://www.weiva.com/archives/163/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/143 http://www.weiva.com/archives/143#respond Wed, 17 Jun 2015 13:16:20 +0000 http://www.weiva.com/?p=143 继续阅读“zend framework2 + Doctrine 中文乱码问题”

    ]]>
    终于成功在项目中安装 Doctrine 了,不过,却发现用 Doctrine 入库的中文都是乱码,虽然用 Doctrine 再次取出恢复正常,但是中感觉缺点什么。
    检查数据表、文件都已经是 UTF8了,唯一可能出现问题的就是 Doctrine 连接的问题,找到 DoctrineDBALDriverPDOMySqlDriver 源代码(这是类路径,要搜索一下),发现:

        /**
         * Constructs the MySql PDO DSN.
         *
         * @param array $params
         *
         * @return string The DSN.
         */
        protected function constructPdoDsn(array $params)
        {
            $dsn = 'mysql:';
            if (isset($params['host']) && $params['host'] != '') {
                $dsn .= 'host=' . $params['host'] . ';';
            }
            if (isset($params['port'])) {
                $dsn .= 'port=' . $params['port'] . ';';
            }
            if (isset($params['dbname'])) {
                $dsn .= 'dbname=' . $params['dbname'] . ';';
            }
            if (isset($params['unix_socket'])) {
                $dsn .= 'unix_socket=' . $params['unix_socket'] . ';';
            }
            if (isset($params['charset'])) {
                $dsn .= 'charset=' . $params['charset'] . ';';
            }
    
            return $dsn;
        }

    关键是:

    $dsn .= 'charset=' . $params['charset'] . ';';

    于是,到文件 doctrine.local.php 添加内容为:

    <?php
    return array(
        'doctrine' => array(
            'connection' => array(
                'orm_default' => array(
                    'driverClass' => 'DoctrineDBALDriverPDOMySqlDriver',
                    'params' => array(
                        'host' => 'localhost',
                        'port' => '',
                        'user' => 'yourusername',
                        'password' => 'yourpassword',
                        'dbname' => 'yourdbname',
                        'charset' => 'UTF8'
                    )
                )
            )
        )
    );

    问题解决

    ]]>
    http://www.weiva.com/archives/143/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/140 http://www.weiva.com/archives/140#respond Fri, 17 Apr 2015 13:15:31 +0000 http://www.weiva.com/?p=140 继续阅读“解决 ZendFramework2 Doctrine 出现 MySql 不支持 enum 类型问题的方法”

    ]]>
    最近项目用 zendFramework 2 + Doctrine,composer 安装完毕后使用 vendor/bin/doctrine-module orm:validate-schema
    命令出现以下错误:

      [DoctrineDBALDBALException]
      Unknown database type enum requested, DoctrineDBALPlatformsMySqlPlatform may not support i
      t.
    

    网上找了很多都是解决在 Symfony 下的,没有发现在 zf2下如何解决,红杏(fanqiang)后终于找到一老外找到了解决办法:
    在 Application 模块(默认模块)的 Module.php 文件添加以下内容:

    class Module {
            public function onBootstrap(MvcEvent $e) {
    
    ......
    
            $em = $e->getApplication()->getServiceManager()->get('DoctrineORMEntityManager');
            $dbPlatform = $em->getConnection()->getDatabasePlatform();
            $dbPlatform->registerDoctrineTypeMapping('enum', 'string');
    
    
    .....
    
    }
    }

    原帖地址:http://foobar.lu/wp/2013/01/24/getting-enum-datatype-to-work-with-doctrine-2-in-zend-framework-2/

    ]]>
    http://www.weiva.com/archives/140/feed 0
    ZendFramewok2 – 微维WeiVa http://www.weiva.com/archives/132 http://www.weiva.com/archives/132#respond Wed, 17 Sep 2014 13:05:53 +0000 http://www.weiva.com/?p=132 继续阅读“zend framework 2 学习笔记:定义自己的日志,记录到数据库中”

    ]]>
    需求:定制自己的日志系统,本例假定指定存储到Mysql数据库当中。

    通常的web我们可以 echo,或者IDE的debuger调试程序,但是有些特殊情况,例如php与android、unity3d等前端通讯时,传统方式并不方便,所以,需要把日志输出到其他地方便于查看。
    * zf2中可以通过指定不同的 Zend/Log/Writer 来使用不同的日志记录方式。

    下面开始动手了
    为了便于在系统中重复使用,我将Logger放到 App 的 Service 中,以后只要在需要的时候,从 Service 中取出就可以用,如果完全没使用,也不会对速度有影响。

    在文件 module/Application/Module.php 中:
    头部引用包:

    use ZendLogLogger;
    use ZendLogWriterDb as WriterDb;

    在 Module 类中,加入自定义 Service:

    public function getServiceConfig(){
            return array(
                'factories'=>array(
                    'WLogger' => function($sm){
                        $dbAdapter = $sm->get ( 'ZendDbAdapterAdapter' ); //需要指定你自己的数据库适配器
                        //对接数据表字段
                        $mapping = array(
                            'timestamp' => 'time',
                            'priority'  => 'type',
                            'message'   => 'message'
                        );
                        $writer = new WriterDb($dbAdapter, 'log_table', $mapping); // log_table 是你自己的日志数据表
                        //$writer = new ZendLogWriterDb($dbAdapter, 'log_table', $mapping); //这样会报错
                        $logger = new Logger();
                        $logger->addWriter($writer);
                        return $logger;
                    }
                )
            );
        }

    添加日志表到你的数据库中:

    --
    -- 表的结构 `log_table`
    --
    
    CREATE TABLE IF NOT EXISTS `log_table` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `type` varchar(255) DEFAULT NULL,
      `message` text,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='日志库' AUTO_INCREMENT=1 ;

    如何使用?:

    $logger = $this->getServiceLocator()->get('WLogger');
    $logger->info('记录一条日志');
    
    ]]>
    http://www.weiva.com/archives/132/feed 0